#pragma once

#include <iostream>
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8081

class HttpServer
{
private:
    int port;
    bool stop;

public:
    HttpServer()
        : port(PORT), stop(false)
    {
    }

    void InitServer()
    {
        // 忽略SIGPIPE信号，如果不忽略可能造成server崩溃(解决写入处理错误)
        signal(SIGPIPE, SIG_IGN);
        TcpServer::GetInstance(port);
    }

    void Loop()
    {
        TcpServer *tcp_svr = TcpServer::GetInstance(port);
        int listen_sock = tcp_svr->Sock();
        LOG(INFO, "Loop start!");
        while (!stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(listen_sock, (struct sockaddr *)&peer, &len);
            if (sock < 0)
            {
                continue;
            }
            LOG(INFO, "Get a new line");
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
        }
    }

    ~HttpServer()
    {
    }
};